package com.atguigu.gmall.order.service;

import com.atguigu.gmall.cart.pojo.Cart;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.order.exception.OrderException;
import com.atguigu.gmall.order.feign.*;
import com.atguigu.gmall.order.interceptor.OrderInterceptor;
import com.atguigu.gmall.order.vo.OrderConfirmVo;
import com.atguigu.gmall.order.vo.OrderItemVo;
import com.atguigu.gmall.order.vo.OrderSunbmitVo;
import com.atguigu.gmall.order.vo.UserInfo;
import com.atguigu.gmall.pms.entity.SkuAttrValueEntity;
import com.atguigu.gmall.pms.entity.SkuEntity;
import com.atguigu.gmall.sms.vo.ItemSaleVo;
import com.atguigu.gmall.ums.entity.UserAddressEntity;
import com.atguigu.gmall.ums.entity.UserEntity;
import com.atguigu.gmall.wms.entity.WareSkuEntity;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderService {
    @Autowired
    private GmallPmsClient pmsClient;
    @Autowired
    private GmallSmsClient smsClient;
    @Autowired
    private GmallWmsClient wmsClient;
    @Autowired
    private GmallUmsClient umsClient;
    @Autowired
    private GmallCartClient cartClient;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String ORDER_TOKEN = "order:token:";

    public OrderConfirmVo confirm() {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        UserInfo userInfo = OrderInterceptor.getUserInfo();
        Long userId = userInfo.getUserId();

        //根据userId查询用户的地址列表
        ResponseVo<List<UserAddressEntity>> userAddressResponseVo = umsClient.queryUserAddress(userId);
        List<UserAddressEntity> userAddressEntities = userAddressResponseVo.getData();
        confirmVo.setAddresses(userAddressEntities);

        //根据userId查询已选中的购物车记录
        ResponseVo<List<Cart>> cartResponseVo = cartClient.queryCartByUserId(userId);
        List<Cart> carts = cartResponseVo.getData();
        if (CollectionUtils.isEmpty(carts)){
            throw new OrderException("没有选中的购物车记录");
        }
        //封装送货清单
        List<OrderItemVo> orderItemVos = carts.stream().map(cart -> {
            OrderItemVo orderItemVo = new OrderItemVo();

            orderItemVo.setSkuId(cart.getSkuId());
            orderItemVo.setCount(cart.getCount());

            //根据skuId查询sku
            ResponseVo<SkuEntity> skuEntityResponseVo = pmsClient.querySkuById(cart.getSkuId());
            SkuEntity skuEntity = skuEntityResponseVo.getData();
            if (skuEntity == null){
                throw new OrderException("商品信息有误");
            }
            orderItemVo.setTitle(skuEntity.getTitle());
            orderItemVo.setPrice(skuEntity.getPrice());
            orderItemVo.setDefaultImage(skuEntity.getDefaultImage());


            //根据skuId查询商品的销售属性
            ResponseVo<List<SkuAttrValueEntity>> skuAttrValueResponseVo =
                    pmsClient.querySkuAttrValueBySKuId(cart.getSkuId());
            List<SkuAttrValueEntity> skuAttrValueEntities = skuAttrValueResponseVo.getData();
            if (CollectionUtils.isEmpty(skuAttrValueEntities)){
                throw new OrderException("商品信息有误");
            }
            //设置商品的销售属性
            orderItemVo.setSaleAttrs(skuAttrValueEntities);


            //根据skuId查询营销信息
            ResponseVo<List<ItemSaleVo>> itemSaleResponseVo = smsClient.querySalesBySkuId(cart.getSkuId());
            List<ItemSaleVo> itemSaleVos = itemSaleResponseVo.getData();
            if (CollectionUtils.isEmpty(itemSaleVos)){
                throw new OrderException("商品信息有误");
            }
            //设置商品的营销信息
            orderItemVo.setSales(itemSaleVos);

            //跟库skuId查询库存信息
            ResponseVo<List<WareSkuEntity>> wareSkuResponseVo = wmsClient.getBySkuId(cart.getSkuId());
            List<WareSkuEntity> wareSkuEntities = wareSkuResponseVo.getData();
            //设置库存信息
            orderItemVo.setStore(wareSkuEntities.stream().anyMatch(wareSkuEntity->
                    wareSkuEntity.getStock() - wareSkuEntity.getStockLocked()>0));


            return orderItemVo;
        }).collect(Collectors.toList());
        //设置送货清单
        confirmVo.setOrderItems(orderItemVos);


        //积分优惠信息
        ResponseVo<UserEntity> userEntityResponseVo = umsClient.queryUserById(userId);
        UserEntity userEntity = userEntityResponseVo.getData();
        if (userEntity == null){
            throw new OrderException("用户参数异常");
        }
        confirmVo.setBounds(userEntity.getIntegration());

        //生成分布式唯一标识
        String orderToken = IdWorker.getIdStr();
        confirmVo.setOrderToken(orderToken);

        //再保存一份在redis中确保幂等性
        redisTemplate.opsForValue().set(ORDER_TOKEN + orderToken,orderToken,30, TimeUnit.MINUTES);

        return  confirmVo;
    }

    public void submit(OrderSunbmitVo orderSunbmitVol) {
        //防重，保证订单的幂等性
        //验总价。获取页面总价和数据库中实时总价对比
        //验库存并锁库存，保证原子性
        //创建订单
        //异步删除购物车中对应的商品记录
    }
}
